import { injectable } from 'inversify';
import { makeAutoObservable } from 'mobx';
import { RolePermission } from './interface.ts';
import { RoleEntity } from './role.entity.ts';
import { roleDetailMapper } from '../mappers/role.list.mapper.ts';

@injectable()
export class RoleListModel {
  private _roles: RoleEntity[] = [];
  private _loading = false;
  private _permissionList: RolePermission[] = [];
  private _permissionLoading = false;

  get roles() {
    return this._roles;
  }

  get loading() {
    return this._loading;
  }

  set loading(value: boolean) {
    this._loading = value;
  }

  get permissionList() {
    return this._permissionList;
  }

  set permissionList(value: RolePermission[]) {
    this._permissionList = value;
  }

  get permissionLoading() {
    return this._permissionLoading;
  }

  set permissionLoading(value: boolean) {
    this._permissionLoading = value;
  }

  constructor() {
    makeAutoObservable(this);
  }

  setRoles(roles: RoleEntity[]) {
    this._roles = roles;
  }

  addRole(role: RoleEntity) {
    this._roles.push(role);
  }

  updateRole(role: RoleEntity) {
    const index = this._roles.findIndex((role) => role._id === role._id);
    if (index > -1) {
      this._roles[index] = roleDetailMapper(role);
    }
  }

  removeRole(_id: string) {
    const index = this._roles.findIndex((role) => role._id === _id);
    if (index > -1) {
      this._roles.splice(index, 1);
    }
  }

  dispose() {
    this._roles = [];
  }
}
